package hephaestus.model.transformer;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;

public class CodeTransformerFromXml extends Transformer {

	public CodeTransformerFromXml(Map initParams) {
		super(initParams);
		// TODO Auto-generated constructor stub
	}

	public void transform(String templateFile,String xmlFile) {
		Writer writer = null;

		try {
			/*
			 * and now call init
			 */

			Velocity.init();

			/*
			 * build a Document from our xml
			 */

			SAXBuilder builder;
			Document root = null;

			try {
				builder = new SAXBuilder();
				root = builder.build(xmlFile);
			} catch (Exception ee) {
				System.out.println("Exception building Document : " + ee);
				return;
			}

			/*
			 * now, make a Context object and populate it.
			 */

			VelocityContext context = new VelocityContext();
			context.put("root", root);

			/*
			 * make a writer, and merge the template 'against' the context
			 */

			Template template = Velocity.getTemplate(templateFile);

			writer = new BufferedWriter(new OutputStreamWriter(System.out));
			template.merge(context, writer);
		} catch (Exception e) {
			System.out.println("Exception : " + e);
		} finally {
			if (writer != null) {
				try {
					writer.flush();
					writer.close();
				} catch (Exception ee) {
					System.out.println("Exception : " + ee);
				}
			}
		}
	}

	@Override
	public void transform() {

	}

	public static void main(String[] args) {
		new CodeTransformerFromXml(null).transform("class.vm","testXml");
	}

	@Override
	public void initialize(Map initParams) {
		// TODO Auto-generated method stub
		
	}
}